package org.summer.lawyer.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.summer.common.core.utils.MapstructUtils;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.lawyer.domain.NimAccount;
import org.summer.lawyer.domain.bo.nimaccount.NimAccountBo;
import org.summer.lawyer.domain.vo.nimaccount.NimAccountVo;
import org.summer.lawyer.im.ImService;
import org.summer.lawyer.im.dto.AccIdCreateDTO;
import org.summer.lawyer.im.dto.AccIdInfoDto;
import org.summer.lawyer.mapper.NimAccountMapper;
import org.summer.lawyer.service.INimAccountService;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 云信账号信息Service业务层处理
 *
 * @author summer
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class NimAccountServiceImpl extends ServiceImpl<NimAccountMapper, NimAccount> implements INimAccountService {

    private final ImService imService;

    /**
     * 查询云信账号信息
     *
     * @param id 主键
     * @return 云信账号信息
     */
    @Override
    public NimAccountVo selectNimAccountVoById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public NimAccountVo selectNimAccountVoByWxUserId(Long wxUserId) {
        LambdaQueryWrapper<NimAccount> lqw = Wrappers.lambdaQuery();
        lqw.eq(NimAccount::getUserId, wxUserId);
        return baseMapper.selectVoOne(lqw, false);
    }

    @Override
    public NimAccountVo selectNimAccountVoByOpenId(String openId) {
        LambdaQueryWrapper<NimAccount> lqw = Wrappers.lambdaQuery();
        lqw.eq(NimAccount::getOpenId, openId);
        NimAccountVo vo = baseMapper.selectVoOne(lqw, false);
        if(vo != null){
            return vo;
        }
        NimAccountBo nimAccountBo = new NimAccountBo();
        nimAccountBo.setOpenId(openId);
        nimAccountBo.setNimType("2");
        nimAccountBo.setNickname("游客");
        this.insertByBo(nimAccountBo);
        return baseMapper.selectVoOne(lqw,false);
    }

    /**
     * 分页查询云信账号信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 云信账号信息分页列表
     */
    @Override
    public TableDataInfo<NimAccountVo> selectPageList(NimAccountBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NimAccount> lqw = buildQueryWrapper(bo);
        Page<NimAccountVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的云信账号信息列表
     *
     * @param bo 查询条件
     * @return 云信账号信息列表
     */
    @Override
    public List<NimAccountVo> selectNimAccountVoList(NimAccountBo bo) {
        LambdaQueryWrapper<NimAccount> lqw = Wrappers.lambdaQuery();
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NimAccount> buildQueryWrapper(NimAccountBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<NimAccount> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, NimAccount::getUserId, bo.getUserId());
        lqw.eq(StrUtil.isNotBlank(bo.getNimType()), NimAccount::getNimType, bo.getNimType());
        lqw.eq(StrUtil.isNotBlank(bo.getAccid()), NimAccount::getAccid, bo.getAccid());
        lqw.eq(StrUtil.isNotBlank(bo.getOpenId()), NimAccount::getOpenId, bo.getOpenId());
        lqw.like(StrUtil.isNotBlank(bo.getNickname()), NimAccount::getNickname, bo.getNickname());
        lqw.eq(StrUtil.isNotBlank(bo.getToken()), NimAccount::getToken, bo.getToken());
        lqw.eq(StrUtil.isNotBlank(bo.getAvatar()), NimAccount::getAvatar, bo.getAvatar());
        return lqw;
    }

    /**
     * 新增云信账号信息
     *
     * @param bo 云信账号信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(NimAccountBo bo) {
        NimAccount add = MapstructUtils.convert(bo, NimAccount.class);
        validEntityBeforeSave(add);
        //调用im接口创建im账号
        AccIdCreateDTO dto = new AccIdCreateDTO();
        dto.setAccid(IdUtil.nanoId(12));
        dto.setName(bo.getNickname());
        if (StrUtil.isNotBlank(bo.getAvatar())) {
            dto.setIcon(bo.getAvatar());
        }
        AccIdInfoDto accIdInfoDto = imService.userCreate(dto);
        add.setAccid(accIdInfoDto.getAccid());
        add.setToken(accIdInfoDto.getToken());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改云信账号信息
     *
     * @param bo 云信账号信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(NimAccountBo bo) {
        NimAccount update = MapstructUtils.convert(bo, NimAccount.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(NimAccount entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除云信账号信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public NimAccountVo selectNimAccountVoByUserId(Long userId) {
        LambdaQueryWrapper<NimAccount> lqw = Wrappers.lambdaQuery();
        lqw.eq(NimAccount::getUserId, userId);
        return baseMapper.selectVoOne(lqw, false);
    }

    @Override
    public NimAccountVo selectNimAccountVoByOpenIdId(String openId) {
        LambdaQueryWrapper<NimAccount> lqw = Wrappers.lambdaQuery();
        lqw.eq(NimAccount::getOpenId, openId);
        return baseMapper.selectVoOne(lqw, false);
    }

    @Override
    public NimAccountVo loadNimAccountVo(NimAccountBo bo) {
        NimAccountVo vo = null;
        if (bo.getUserId() != null) {
            vo = selectNimAccountVoByUserId(bo.getUserId());
        } else {
            vo = selectNimAccountVoByOpenIdId(bo.getOpenId());
        }
        if (ObjectUtil.isNotNull(vo)) {
            if (StrUtil.isEmpty(vo.getAccid()) || StrUtil.isEmpty(vo.getToken())) {
                baseMapper.deleteById(vo.getId());
            } else {
                return vo;
            }
        }
        this.insertByBo(bo);
        return selectNimAccountVoById(bo.getId());
    }
}
